#pragma once

#include "share_mem_include.h"
#include <assert.h>

namespace anet {
	namespace SShareMemorySpace {
		class CShareMemory {
		public:
			CShareMemory() : m_shmKey(-1), m_pshm(nullptr),
				m_shmId(0), m_shmSize(0), m_create(false) {
			}
			CShareMemory(key_t key, size_t size) {
				bool ret = CreateShareMem(key, size);
				assert(ret && "create share memory error");
			}

			// just to detach share memory
			virtual ~CShareMemory() {
				if (m_create) {
					this->Detach();
					this->Delete();
				}
			}

		public:
			// create share memory
			// key is key for the only share memory identity
			// size is for allocating share memory size
			bool   CreateShareMem(key_t key, size_t memSize);

			// Open share memory
			bool   OpenShareMem(key_t key, size_t memSize);

			// Detach share memory
			int    Detach();

			// Delete share memory.
			int    Delete();

			// is create 
			bool   IsCreate() const { return m_create; }

			// get share memory pointer
			void*  GetMemory() { return m_pshm; }

			// Get share memory size
			size_t GetShareMemSize() { return m_shmSize; }

		protected:
			key_t      m_shmKey;  // share memory primary key
			void*      m_pshm;    // share memory address
			shmid      m_shmId;   // share memory id
			size_t     m_shmSize; // share memory size
			bool       m_create;  // whether it is created
		};
	}
}